﻿using Loaf.Beans;
using Loaf.Tools;
using Loaf.Views;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.IO.Compression;
using Prism.Services.Dialogs;

namespace Loaf.ViewModels
{
    public class BookshelfViewModel : BindableBase
    {
        private IContainerProvider Container;
        private List<SearchModel> searchModels;
        private string filter;
        private string tip;
        private bool breakDownload;
        private Visibility breakDownloadVisibility;

        public Context Context { get; set; }

        /// <summary>
        /// 搜索条件
        /// </summary>
        public string Filter { get => filter; set { filter = value; RaisePropertyChanged(); } }
        /// <summary>
        /// 搜索结果
        /// </summary>
        public List<SearchModel> SearchModels { get => searchModels; set { searchModels = value; RaisePropertyChanged(); } }
        /// <summary>
        /// 如果搜索结果为空，则提示用户
        /// </summary>
        public string Tip { get => tip; set { tip = value; RaisePropertyChanged(); } }
        /// <summary>
        /// 暂停下载按钮得显隐
        /// </summary>
        public Visibility BreakDownloadVisibility { get => breakDownloadVisibility; set { breakDownloadVisibility = value; RaisePropertyChanged(); } }

        public DelegateCommand SearchCommand { get; set; }
        public DelegateCommand<SearchModel> AddBookCommand { get; set; }

        public DelegateCommand<Book> ReadBookCommand { get; set; }
        public DelegateCommand<Book> DeleteBookCommand { get; set; }

        public DelegateCommand<SearchModel> DownloadTxtCommand { get; set; }
        public DelegateCommand BreakDownloadCommand { get; set; }

        public DelegateCommand ImportCommand { get; set; }

        public BookshelfViewModel(Context context, IContainerProvider container)
        {
            Context = context;
            Container = container;
            breakDownload = false;
            BreakDownloadVisibility = Visibility.Hidden;

            SearchCommand = new DelegateCommand(SearchAction);
            AddBookCommand = new DelegateCommand<SearchModel>(AddBookAction);
            ReadBookCommand = new DelegateCommand<Book>(ReadBookAction);
            DeleteBookCommand = new DelegateCommand<Book>(DeleteBookAction);
            DownloadTxtCommand = new DelegateCommand<SearchModel>(DownloadTxtAction);
            BreakDownloadCommand = new DelegateCommand(() => breakDownload = true);
            ImportCommand = new DelegateCommand(ImportAction);
        }

        /// <summary>
        /// 搜索书籍
        /// </summary>
        public async void SearchAction()
        {
            if (string.IsNullOrWhiteSpace(Filter))
                return;

            Tip = "正在搜索，请稍后";
            SearchModels = await HtmlTool.GetSearchResult(Filter);

            Filter = "";
            if (SearchModels.Count == 0)
                Tip = "搜索结果为空，请注意书籍是否是全称";
            else
                Tip = "搜索完成，点击符号 + 即可添加进书架";
        }

        /// <summary>
        /// 将书籍添加进书架
        /// </summary>
        /// <param name="model"></param>
        public async void AddBookAction(SearchModel model)
        {
            Context.BookSetting.BookList.Add(new Book()
            {
                BookName = model.BookName,
                CurrIndex = 0,
                DictUrl = model.BookUrl,
                Offset = 0,
                WebsiteType = model.WebsiteType
            });
            Context.WriteContext();
            Tip = "添加成功，可继续添加";
            await Task.Delay(TimeSpan.FromSeconds(10));
            Tip = "";
        }

        /// <summary>
        /// 阅读某个书籍
        /// </summary>
        /// <param name="book"></param>
        public void ReadBookAction(Book book)
        {
            Context.BookSetting.LastBook = book;
            Context.WriteContext();

            Context.ReaderWindow = Container.Resolve<ReaderWindow>();
            Context.ReaderWindow.Show();
        }

        /// <summary>
        /// 删除某个书籍
        /// </summary>
        /// <param name="book"></param>
        public void DeleteBookAction(Book book)
        {
            var result = MessageBox.Show("确定删除吗", "提示", MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                Context.BookSetting.BookList.Remove(book);
                Context.WriteContext();
            }
        }

        /// <summary>
        /// 下载txt并添加到书架
        /// </summary>
        public async void DownloadTxtAction(SearchModel model)
        {
            BreakDownloadVisibility = Visibility.Visible;

            Directory.CreateDirectory("./Resources/" + model.BookName);

            Context.BookSetting.BookList.Add(new Book()
            {
                BookName = model.BookName,
                CurrIndex = 0,
                DictUrl = model.BookName + "/dictionary",
                Offset = 0,
                WebsiteType = WebsiteType.本地
            });
            Context.WriteContext();
            await Task.Run(async () =>
            {
                var dict = HtmlTool.GetHtmlDictionary(model.BookUrl, model.WebsiteType);//请求获取目录
                var newDict = JsonTool.ReadJson<List<BookDictionary>>(model.BookName + "/dictionary");//本地已经解析的目录


                for (int index = newDict.Count; index < dict.Count; index++)
                {
                    var path = "./Resources/" + model.BookName + "/" + dict[index].Title + ".txt";
                    var content = HtmlTool.GetHtmlText(dict[index].Url, model.WebsiteType);

                    Tip = dict[index].Title;

                    newDict.Add(new BookDictionary()
                    {
                        Title = dict[index].Title,
                        Url = path
                    });
                    File.WriteAllText(path, content);

                    if (breakDownload)
                        break;
                }
                JsonTool.WriteJson(newDict, model.BookName + "/dictionary");
            });
            Tip = "";
            BreakDownloadVisibility = Visibility.Hidden;
            breakDownload = false;
        }

        /// <summary>
        /// 导入书籍功能
        /// </summary>
        public void ImportAction()
        {

            OpenFolderDialog dialog = new OpenFolderDialog();

            if (dialog.ShowDialog() == true)
            {
                try
                {
                    var path = dialog.FolderName;
                    int first = path.LastIndexOf("\\") + 1;
                    var bookName = path.Substring(first, path.Length - first);

                    Context.BookSetting.BookList.Add(new Book()
                    {
                        BookName = bookName,
                        CurrIndex = 0,
                        DictUrl = bookName + "/dictionary",
                        Offset = 0,
                        WebsiteType = WebsiteType.本地
                    });
                    Context.WriteContext();
                }
                catch { }
            }
        }
    }
}
